package com.example.android.ouactivity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.ouactivity.adapter.ViewPagerAdapter;
import com.example.android.ouactivity.login_register.About;
import com.example.android.ouactivity.login_register.Login;
import com.example.android.ouactivity.model.User;
import com.example.android.ouactivity.utils.ReadUserInfo;
import com.example.android.ouactivity.utils.SnackbarUtil;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, View.OnClickListener, SearchView.OnQueryTextListener, NavigationView.OnNavigationItemSelectedListener {

    //初始化各种控件，照着xml中的顺序写的
    private DrawerLayout mDrawerLayout;
    private Toolbar mToolbar;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private FloatingActionButton mFloatingActionButton;
    private NavigationView mNavigationView;


    // TabLayout中的tab标题
    private String[] mTabTitle;
    // 填充到ViewPager中的Fragment
    private List<Fragment> mFragments;
    //toolbar 中的 搜索
    private SearchView searchView;
    Intent intent;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化各种控件
        initViews();

        initFragDataToViewPager();
        configViews();

    }


    private void initViews() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawerlayout);
        mToolbar = (Toolbar) findViewById(R.id.id_toolbar);
        mTabLayout = (TabLayout) findViewById(R.id.id_tablayout);
        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
        mFloatingActionButton = (FloatingActionButton) findViewById(R.id.id_floatingactionbutton);
        mNavigationView = (NavigationView) findViewById(R.id.id_navigationview);
    }

    private void initFragDataToViewPager() {

        // Tab的标题采用string-array的方法保存，在res/values/arrays.xml中写
        mTabTitle = getResources().getStringArray(R.array.tab_titles);

        //初始化填充到ViewPager中的Fragment集合
        mFragments = new ArrayList<>();
        String[] arr = new String[mTabTitle.length];
        for (int i = 0; i < mTabTitle.length; i++) {
            arr[i] = "http://www.chqing.cn/content?type="+i;
            MainFragment mFragment = new MainFragment(arr[i]);
            mFragments.add(i, mFragment);
        }

    }

    private void configViews() {

        configDrawerIcon();

        configNavigationView();

        configTabLayout();

        // 设置FloatingActionButton的点击事件
        mFloatingActionButton.setOnClickListener(this);
    }

    private void configDrawerIcon() {
        // 设置显示Toolbar
        setSupportActionBar(mToolbar);

        //设置标题
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("最近活动");
        }


        // 设置Drawerlayout开关指示器，即Toolbar最左边的那个icon
        ActionBarDrawerToggle mActionBarDrawerToggle =
                new ActionBarDrawerToggle(
                        this,
                        mDrawerLayout,
                        mToolbar,
                        R.string.open,
                        R.string.close
                ) {

                    /** Called when a drawer has settled in a completely closed state. */
                    public void onDrawerClosed(View view) {
                        super.onDrawerClosed(view);
                        //Toast.makeText(getApplicationContext(), "已关闭",Toast.LENGTH_SHORT).show();
                    }

                    /** Called when a drawer has settled in a completely open state. */
                    public void onDrawerOpened(View drawerView) {


                        super.onDrawerOpened(drawerView);
                        //Toast.makeText(getApplicationContext(), "已打开", Toast.LENGTH_SHORT).show();
                    }
                };

        mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
        //显示开关侧滑栏的按钮
        mActionBarDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
    }

    private void configTabLayout() {
        // 初始化ViewPager的适配器，并设置给它
        ViewPagerAdapter mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mTabTitle, mFragments);
        mViewPager.setAdapter(mViewPagerAdapter);

        // 设置ViewPager最大缓存的页面个数
        mViewPager.setOffscreenPageLimit(3);

        // 给ViewPager添加页面动态监听器
        // （为了让Toolbar中的Title可以变化相应的Tab的标题）
        mViewPager.addOnPageChangeListener(this);
        //mTabLayout.setTabMode(MODE_SCROLLABLE);


        //TabLayout 与 ViewPager 建立关联
        /**
         *设置后 TabLayout 将自动检索 ViewPager
         * 设置适配器里的 getCount() 数量来新建 Tab 个数，
         * getPageTitle()方法设置 Tab 的 text 属性，
         * 且把 Tab 的点击事件与ViewPager的 Item建立关联
         */
        // 将TabLayout和ViewPager进行关联，让两者联动起来
        mTabLayout.setupWithViewPager(mViewPager);

        // 设置Tablayout的Tab显示ViewPager的适配器中的getPageTitle函数获取到的标题
        mTabLayout.setTabsFromPagerAdapter(mViewPagerAdapter);

    }

    private void configNavigationView() {

        //给NavigationView填充顶部区域
        mNavigationView.inflateHeaderView(R.layout.header_nav);

        //给NavigationView填充Menu菜单
        mNavigationView.inflateMenu(R.menu.menu_nav);

        //设置NavigationView中menu的item被选中后要执行的操作
        mNavigationView.setNavigationItemSelectedListener(this);

        //给头像加监听
        View headerView = mNavigationView.getHeaderView(0);
//        intent = new Intent(this,ItemWebActivity.class);
        ImageView headFace = (ImageView) headerView.findViewById(R.id.id_header_face);
        TextView name = (TextView) headerView.findViewById(R.id.id_header_authorname) ;
        TextView tip = (TextView) headerView.findViewById(R.id.id_header_url);
        ReadUserInfo read = new ReadUserInfo(this,"userInfo");
        final String result = read.getInfo();
        if(!result.equals("")){
            User user = new User();
            user.setId(result.split(",")[0]);
            user.setName(result.split(",")[1]);
            user.setImage(result.split(",")[2]);
            headFace.setImageResource(R.drawable.a);
            name.setText(user.getName());
            tip.setHeight(0);
        }
        headFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(result.equals("")){
                    Intent login = new Intent(MainActivity.this, Login.class);
                    startActivity(login);
                }else {
                    Toast.makeText(MainActivity.this,"此功能尚未完善",Toast.LENGTH_SHORT).show();
                }
                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.id_drawerlayout);
                drawer.closeDrawer(GravityCompat.START);
            }
        });

    }


    //toolbar菜单创建时调用
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_toolbar, menu);

        //1.查找指定的MemuItem
        MenuItem menuItem = menu.findItem(R.id.action_search);

        //2.设置SearchView v7包方式
        View view = MenuItemCompat.getActionView(menuItem);
        if (view != null) {
            searchView = (SearchView) view;
            //4.设置SearchView 的查询回调接口
            searchView.setOnQueryTextListener(this);

            //在搜索输入框没有显示的时候 点击Action ,回调这个接口，并且显示输入框
            //searchView.setOnSearchClickListener();
            //当自动补全的内容被选中的时候回调接口
            //searchView.setOnSuggestionListener();
            //可以设置搜索的自动补全，或者实现搜索历史
            //searchView.setSuggestionsAdapter();
        }

        return super.onCreateOptionsMenu(menu);
    }

    //toolbar 的按钮被选中时调用
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            Intent login = new Intent(MainActivity.this, About.class);
            startActivity(login);
        }

        return super.onOptionsItemSelected(item);
    }

    //ViewPage被选中时，将toolbal的Title设置为和Tab的Title一样
    @Override
    public void onPageSelected(int position) {

        //mToolbar.setTitle(mTabTitle[position]);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    //当用户在输入法中点击搜索按钮时,或者输入回车时,调用这个方法，发起实际的搜索功能
    @Override
    public boolean onQueryTextSubmit(String query) {
        Toast.makeText(MainActivity.this, "Submit" + query, Toast.LENGTH_SHORT).show();

        searchView.clearFocus();
        return true;
    }

    //每一次输入字符，都会调用这个方法，实现搜索的联想功能
    @Override
    public boolean onQueryTextChange(String newText) {
        Toast.makeText(MainActivity.this, "" + newText, Toast.LENGTH_SHORT).show();
        return true;
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        String msgString = "";
        ReadUserInfo read = new ReadUserInfo(this,"userInfo");
        switch (menuItem.getItemId()) {
            case R.id.nav_menu_home:
                msgString = (String) menuItem.getTitle();
                break;
            case R.id.nav_menu_categories:
                msgString = (String) menuItem.getTitle();
                break;
            case R.id.nav_menu_feedback:
                msgString = (String) menuItem.getTitle();
                //暂时用这个监听做了消息的监听
                if(read.hasFile()){
                    Intent msg = new Intent(MainActivity.this, MessageActivity.class);
                    startActivity(msg);
                }else {
                    Toast.makeText(this,"Please login!",Toast.LENGTH_SHORT).show();
                    Intent login = new Intent(MainActivity.this, Login.class);
                    startActivity(login);
                }
                break;
            case R.id.nav_menu_setting:
                msgString = (String) menuItem.getTitle();
                break;
            case R.id.nav_menu_logout:
                if(read.deleteInfo()){
                    Toast.makeText(MainActivity.this,"你已退出账号",Toast.LENGTH_SHORT).show();
                    Intent main = new Intent(MainActivity.this,MainActivity.class);
                    startActivity(main);
                }
                break;
        }

        // Menu item点击后选中，
        menuItem.setChecked(true);
        //关闭Drawerlayout
        mDrawerLayout.closeDrawer(GravityCompat.START);
        // android-support-design兼容包中新添加的一个类似Toast的控件。
        SnackbarUtil.show(mViewPager, msgString, 0);
        return true;
    }

    //手机返回键关闭侧边栏
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.id_drawerlayout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // FloatingActionButton的点击事件
            case R.id.id_floatingactionbutton:
                SnackbarUtil.show(v, getString(R.string.plusone), 0);
                break;
        }
    }
}
